﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Altbrot.Yawr.Entities;

namespace Altbrot.Yawr.Rss
{
    public class RssParser : IFeedParser
    {
        #region IFeedParser Members

        public List<FeedItem> Parse(string url, FeedItemCategory category)
        {
            try
            {
                XDocument feed = XDocument.Load(url);

                if (feed.Elements().Count() == 0) return null;

                XNamespace ns = "http://purl.org/rss/1.0/modules/slash/";

                string source = (from ele in feed.Descendants("channel").Elements("title") select ele.Value).Single();

                List<FeedItem> items = (from item in feed.Descendants("item")
                                        select new FeedItem
                                        {
                                            Title = item.Element("title").Value,
                                            PubDate = (item.Element("pubDate") != null ? (DateTime?)Convert.ToDateTime(item.Element("pubDate").Value) : null),
                                            Link = item.Element("link").Value,
                                            Description = (item.Element("description") != null ? item.Element("description").Value : ""),
                                            Guid = (item.Element("guid") != null ? item.Element("guid").Value : item.Element("link").Value),
                                            Source = source,
                                            Category = category.ToString()
                                        }).ToList();

                return items;
            }
            catch
            {
                return null;
            }
        }

        #endregion
    }

}
